package ui;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import java.util.Scanner;
import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.sql.Connection;

import entity.SchoolClass;
import dao.ClassDAO;
import entity.User;
import entity.Lab;
import entity.LabReservation;
import dao.LabDAO;
import dao.LabReservationDAO;
import dao.UserDAO;
import util.JDBCUtil;

public class TeacherUI {
    private final Scanner scanner = new Scanner(System.in);
    private final LabDAO labDAO = new LabDAO();
    private final LabReservationDAO reservationDAO = new LabReservationDAO();
    private final UserDAO userDAO = new UserDAO();
    private final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    private final User currentUser;

    public TeacherUI(User currentUser) {
        this.currentUser = currentUser;
    }

    public void showMenu() {
        while (true) {
            System.out.println("\n=== 教师菜单 ===");
            System.out.println("1. 查看实验室可用情况");
            System.out.println("2. 查看学生使用情况");
            System.out.println("3. 预约实验室");
            System.out.println("4. 查看我的预约");
            System.out.println("5. 班级管理"); // 新增选项
            System.out.println("6. 退出");
            System.out.print("请选择操作：");

            int choice = scanner.nextInt();
            scanner.nextLine();

            switch (choice) {
                case 1:
                    checkLabAvailability();
                    break;
                case 2:
                    viewStudentUsage();
                    break;
                case 3:
                    reserveLab();
                    break;
                case 4:
                    viewMyReservations();
                    break;
                case 5:
                    classManagement(); // 新增方法
                    break;
                case 6:
                    return;
                default:
                    System.out.println("无效选择");
            }
        }
    }

    // 查看实验室可用情况
    private void checkLabAvailability() {
        System.out.println("\n=== 实验室可用情况 ===");
        labDAO.listAllLabs().forEach(lab ->
                System.out.printf("ID: %d, 名称: %s, 状态: %s, 容量: %d\n",
                        lab.getLabId(), lab.getLabName(), lab.getStatus(), lab.getCapacity())
        );
    }

    // 查看学生使用情况
    private void viewStudentUsage() {
        System.out.print("请输入实验室ID：");
        int labId = scanner.nextInt();
        scanner.nextLine();

        System.out.println("\n=== 该实验室学生使用记录 ===");
        reservationDAO.getReservationsByLab(labId).forEach(res -> {
            User user = userDAO.getUserById(res.getUserId());
            if (user.getRole().equals("student")) {
                System.out.printf("学生姓名: %s（ID: %d）, 时间: %s - %s, 用途: %s\n",
                        user.getRealName(), user.getUserId(),
                        sdf.format(res.getStartTime()), sdf.format(res.getEndTime()),
                        res.getPurpose() == null ? "无" : res.getPurpose());
            }
        });
    }

    // 预约实验室
    private void reserveLab() {
        System.out.print("请输入实验室ID：");
        int labId = scanner.nextInt();
        scanner.nextLine();

        Lab lab = labDAO.getLabById(labId);
        if (lab == null) {
            System.out.println("实验室不存在");
            return;
        }

        System.out.print("请输入开始时间（格式yyyy-MM-dd HH:mm）：");
        String startStr = scanner.nextLine();
        System.out.print("请输入结束时间（格式yyyy-MM-dd HH:mm）：");
        String endStr = scanner.nextLine();
        System.out.print("请输入使用目的：");
        String purpose = scanner.nextLine();

        try {
            Date startTime = sdf.parse(startStr);
            Date endTime = sdf.parse(endStr);

            LabReservation reservation = new LabReservation();
            reservation.setLabId(labId);
            reservation.setUserId(currentUser.getUserId());
            reservation.setStartTime(startTime);
            reservation.setEndTime(endTime);
            reservation.setPurpose(purpose);

            if (reservationDAO.addReservation(reservation)) {
                lab.setStatus("occupied");
                labDAO.updateLab(lab);
                System.out.println("实验室预约成功");
            } else {
                System.out.println("时间段冲突，预约失败");
            }
        } catch (ParseException e) {
            System.out.println("时间格式错误");
        }
    }

    // 查看我的预约
    private void viewMyReservations() {
        System.out.println("\n=== 我的预约记录 ===");
        reservationDAO.getReservationsByUser(currentUser.getUserId()).forEach(res -> {
            Lab lab = labDAO.getLabById(res.getLabId());
            System.out.printf("实验室: %s（ID: %d）, 时间: %s - %s, 用途: %s\n",
                    lab.getLabName(), lab.getLabId(),
                    sdf.format(res.getStartTime()), sdf.format(res.getEndTime()),
                    res.getPurpose() == null ? "无" : res.getPurpose());
        });
    }

    private void classManagement() {
        ClassDAO classDAO = new ClassDAO();
        UserDAO userDAO = new UserDAO();

        while (true) {
            System.out.println("\n=== 班级管理 ===");
            System.out.println("1. 创建班级");
            System.out.println("2. 查看我的班级");
            System.out.println("3. 添加学生到班级");
            System.out.println("4. 查看班级学生");
            System.out.println("5. 返回主菜单");
            System.out.print("请选择操作：");

            int choice = scanner.nextInt();
            scanner.nextLine();

            switch (choice) {
                case 1:
                    createClass(classDAO);
                    break;
                case 2:
                    viewMyClasses(classDAO);
                    break;
                case 3:
                    addStudentToClass(classDAO, userDAO);
                    break;
                case 4:
                    viewClassStudents(classDAO, userDAO);
                    break;
                case 5:
                    return;
                default:
                    System.out.println("无效选择");
            }
        }
    }

    private void createClass(ClassDAO classDAO) {
        System.out.print("请输入班级ID：");
        int classId = scanner.nextInt();
        scanner.nextLine();

        System.out.print("请输入班级名称：");
        String className = scanner.nextLine();

        SchoolClass clazz = new SchoolClass();
        clazz.setClassId(classId);
        clazz.setClassName(className);
        clazz.setTeacherId(currentUser.getUserId());

        if (classDAO.addClass(clazz)) {
            System.out.println("班级创建成功");
        } else {
            System.out.println("班级创建失败");
        }
    }

    private void viewMyClasses(ClassDAO classDAO) {
        System.out.println("\n=== 我的班级 ===");
        String sql = "SELECT * FROM class WHERE teacher_id = ?";
        try (Connection conn = JDBCUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setInt(1, currentUser.getUserId());
            ResultSet rs = pstmt.executeQuery();
            while (rs.next()) {
                System.out.printf("班级ID: %d, 班级名称: %s\n",
                        rs.getInt("class_id"), rs.getString("class_name"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    private void addStudentToClass(ClassDAO classDAO, UserDAO userDAO) {
        System.out.print("请输入班级ID：");
        int classId = scanner.nextInt();
        scanner.nextLine();

        System.out.print("请输入学生ID：");
        int studentId = scanner.nextInt();
        scanner.nextLine();

        // 检查学生是否存在
        User student = userDAO.getUserById(studentId);
        if (student == null || !"student".equals(student.getRole())) {
            System.out.println("学生不存在或ID不正确");
            return;
        }

        // 检查班级是否存在且属于当前老师
        SchoolClass clazz = classDAO.getClassById(classId);
        if (clazz == null || clazz.getTeacherId() != currentUser.getUserId()) {
            System.out.println("班级不存在或您不是该班级的老师");
            return;
        }

        // 更新学生的class_id
        String sql = "UPDATE user SET class_id = ? WHERE user_id = ?";
        try (Connection conn = JDBCUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setInt(1, classId);
            pstmt.setInt(2, studentId);
            if (pstmt.executeUpdate() > 0) {
                System.out.println("学生添加成功");
            } else {
                System.out.println("学生添加失败");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    // 查看班级学生
    private void viewClassStudents(ClassDAO classDAO, UserDAO userDAO) {
        System.out.print("请输入班级ID：");
        int classId = scanner.nextInt();
        scanner.nextLine();

        // 检查班级是否存在且属于当前老师
        SchoolClass clazz = classDAO.getClassById(classId);
        if (clazz == null || clazz.getTeacherId() != currentUser.getUserId()) {
            System.out.println("班级不存在或您不是该班级的老师");
            return;
        }

        System.out.println("\n=== 班级学生列表 ===");
        String sql = "SELECT * FROM user WHERE class_id = ?";
        try (Connection conn = JDBCUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setInt(1, classId);
            ResultSet rs = pstmt.executeQuery();
            while (rs.next()) {
                System.out.printf("学生ID: %d, 姓名: %s, 用户名: %s\n",
                        rs.getInt("user_id"), rs.getString("real_name"), rs.getString("username"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }
}
